package com.tomshidi.security.distributed.uaa.sms;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author chenzhihua@skyworth.com
 * @version 1.0
 * @since 2022/5/12 16:18
 */

public class SmsAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsAuthenticationToken sat = (SmsAuthenticationToken)authentication;
        String phone = (String) sat.getPrincipal();

        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);

        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("用户信息不存在");
        }

        SmsAuthenticationToken result =
                new SmsAuthenticationToken(userDetails.getUsername(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;

    }




    @Override
    public boolean supports(Class<?> authentication) {
        return SmsAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
